﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;
using MESCodeFile;
using LiveNotificationSystem;
using System.Drawing.Printing;
namespace mes_tublay
{
    public partial class frmTreasuryPayment : Form
    {
        string firstcode, m;
        int q, ctr=0;
        decimal amt, paymade, qtrpay=0;
        public frmTreasuryPayment()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            frmTreasuryPayment_Load();
            optquarterly.Click += new EventHandler(optquarterly_Click);
            optannual.Click += new EventHandler(optannual_Click);
            btnsavepayment.Click += new EventHandler(btnsavepayment_Click);
            btnprintreceipt.Click += new EventHandler(btnprintreceipt_Click);
            //Check quarters that are selected
            chksecond.Click += new EventHandler(chksecond_Click);
            chkthird.Click += new EventHandler(chkthird_Click);
            chkfourth.Click += new EventHandler(chkfourth_Click);
        }

        void chkfourth_Click(object sender, EventArgs e)
        {
            ctr++;
            if (chkfourth.Checked == true && chkfourth.Enabled == true)
            {
                qtrpay = (amt * 4) - paymade;
            }
            else
            {
                qtrpay = (amt * 3) - paymade;
            }
            lbltotalamountdue.Text = qtrpay.ToString();
            txtamtpaid.Value = qtrpay;
        }

        void chkthird_Click(object sender, EventArgs e)
        {
            ctr++;
            if (chkthird.Checked == true && chkthird.Enabled == true)
            {
                chkfourth.Enabled = true;
                qtrpay = (amt * 3) - paymade;
            }
            else
            {
                chkfourth.Enabled = false;
                qtrpay = (amt * 2) - paymade;
            }
            lbltotalamountdue.Text = qtrpay.ToString();
            txtamtpaid.Value = qtrpay;
        }

        void chksecond_Click(object sender, EventArgs e)
        {
            ctr++;
            if (chksecond.Checked == true && chksecond.Enabled==true)
            {
                chkthird.Enabled = true;
                qtrpay = (amt * 2) - paymade;
            }
            else
            {
                chkthird.Enabled = false;
                qtrpay = amt;
            }
            lbltotalamountdue.Text = qtrpay.ToString();
            txtamtpaid.Value = qtrpay;
        }

        void optannual_Click(object sender, EventArgs e)
        {
            chkfirst.Checked = false;
            chkfirst.Enabled = false;
            chksecond.Checked = false;
            chksecond.Enabled = false;
            chkthird.Checked = false;
            chkthird.Enabled = false;
            chkfourth.Checked = false;
            chkfourth.Enabled = false;
            lbltotalamountdue.Text = lblbalance.Text;
            txtamtpaid.Value = Decimal.Parse(lblbalance.Text);
            ctr = 0;
        }

        void btnprintreceipt_Click(object sender, EventArgs e)
        {
            printreceipt();
        }

        void btnsavepayment_Click(object sender, EventArgs e)
        {
            DialogResult submit = MessageBox.Show("Save Transaction?", "Confirm Payment", MessageBoxButtons.OKCancel);
            if (submit == DialogResult.OK)
            {
                string ap, fn, td, mp, orno;
                int cy;
                double amount;
                ap = lblApplicationNumber.Text;
                fn = lblfullname.Text;
                cy = int.Parse(txtcalyr.Text);
                td = txtdatepayment.Value.ToString("yyyy-MM-dd");
                orno = lblorno.Text;
                amount = Double.Parse(txtamtpaid.Value.ToString());
                if (optannual.Checked == true)
                {
                    mp = "Annually";
                }
                else
                {
                    mp = "Quarterly";
                    if (chkfirst.Checked == true)
                    {
                        q = 1;
                    }
                    else if (chksecond.Checked == true)
                    {
                        q = 2;
                    }
                    else if (chkthird.Checked == true)
                    {
                        q = 3;
                    }
                    else if (chkfourth.Checked == true)
                    {
                        q = 4;
                    }
                    else
                    {
                        q = 0;
                    }
                }
                CodeProcessor p = new CodeProcessor(ThreadingMode.Exclusive);
                if (p.State != ProcessorFlag.Ready && p.State != ProcessorFlag.DataRdy) return;
                CodeScript s = new CodeScript("SAVEPAY");
                s.Add(CodeIns.SYS_RESET);
                s.Add(CodeIns.DBU_NEW_CORE);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
                s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
                if (mp.Equals("Annually"))
                {
                    s.Add(CodeIns.DBU_INSERT, "tblpayment",
                      new string[] { "fApplicationNumber", "fCalYear", "fFullName", "fTransDate", "fMannerPayment",
                        "fORNo","fAmountPaid","quarter"},
                      new object[] {"'"+ap+"'","'"+cy+"'","'"+fn+"'","'"+td+"'","'"+mp+"'",
                        "'"+orno+"'","'"+amount+"'","'"+q+"'"});
                }
                else
                {
                    if(chkfirst.Checked==true && chkfirst.Enabled==true)
                    {
                        q = 1;
                        s.Add(CodeIns.DBU_INSERT, "tblpayment",
                      new string[] { "fApplicationNumber", "fCalYear", "fFullName", "fTransDate", "fMannerPayment",
                        "fORNo","fAmountPaid","quarter"},
                      new object[] {"'"+ap+"'","'"+cy+"'","'"+fn+"'","'"+td+"'","'"+mp+"'",
                        "'"+orno+"'","'"+amt+"'","'"+q+"'"});
                    }
                    if (chksecond.Checked == true && chksecond.Enabled == true)
                    {
                        q = 2;
                        s.Add(CodeIns.DBU_INSERT, "tblpayment",
                      new string[] { "fApplicationNumber", "fCalYear", "fFullName", "fTransDate", "fMannerPayment",
                        "fORNo","fAmountPaid","quarter"},
                      new object[] {"'"+ap+"'","'"+cy+"'","'"+fn+"'","'"+td+"'","'"+mp+"'",
                        "'"+orno+"'","'"+amt+"'","'"+q+"'"});
                    }
                    if (chkthird.Checked == true && chkthird.Enabled == true)
                    {
                        q = 3;
                        s.Add(CodeIns.DBU_INSERT, "tblpayment",
                      new string[] { "fApplicationNumber", "fCalYear", "fFullName", "fTransDate", "fMannerPayment",
                        "fORNo","fAmountPaid","quarter"},
                      new object[] {"'"+ap+"'","'"+cy+"'","'"+fn+"'","'"+td+"'","'"+mp+"'",
                        "'"+orno+"'","'"+amt+"'","'"+q+"'"});
                    }
                    if (chkfourth.Checked == true && chkfourth.Enabled == true)
                    {
                        q = 4;
                        s.Add(CodeIns.DBU_INSERT, "tblpayment",
                      new string[] { "fApplicationNumber", "fCalYear", "fFullName", "fTransDate", "fMannerPayment",
                        "fORNo","fAmountPaid","quarter"},
                      new object[] {"'"+ap+"'","'"+cy+"'","'"+fn+"'","'"+td+"'","'"+mp+"'",
                        "'"+orno+"'","'"+amt+"'","'"+q+"'"});
                    }
                }
                s.Add(CodeIns.DBU_END);
                p.Run(s);
                btnprintreceipt.Enabled = true;
                MessageBox.Show("Payment Saved");
                btnsavepayment.Enabled = false;
            }
            else
            {
                MessageBox.Show("Payment is not saved!", "Transaction Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        public void GetAppNumber(string apno, string fn, string totalassess)
        {
            lblApplicationNumber.Text = apno;
            lblfullname.Text = fn;
            lbltotalassessedtax.Text = totalassess;
        }
        void optquarterly_Click(object sender, EventArgs e)
        {
            ctr++;
            chkfirst.Checked = true;
            chkfirst.Enabled = true;
            chksecond.Enabled = true;
            decimal assessedtax;
            assessedtax = Decimal.Parse(lbltotalassessedtax.Text);
            lbltotalamountdue.Text = amt.ToString();
            txtamtpaid.Value = amt;
        }
        private void frmTreasuryPayment_Load()
        {
            optannual.Checked = true;
            chkfirst.Enabled = false;
            chksecond.Enabled = false;
            chkthird.Enabled = false;
            chkfourth.Enabled = false;
            btnprintreceipt.Enabled = false;
            firstcode = DateTime.Now.Year.ToString();
            int cyear = int.Parse(firstcode) - 1;
            txtcalyr.Text = cyear.ToString();
            getnextorno();
            checkpreviouspayment();
            gettotal();
            amt = Decimal.Parse(lbltotalassessedtax.Text) / 4;
        }
        void checkpreviouspayment()
        {
            string apno = lblApplicationNumber.Text;
            CodeProcessor p = new CodeProcessor(ThreadingMode.Exclusive);
            if (p.State != ProcessorFlag.Ready && p.State != ProcessorFlag.DataRdy) return;
            CodeScript s = new CodeScript("CHECKPAY");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

            s.Add(CodeIns.DBU_QUERY, "Select * from tblpayment  where fApplicationNumber='" + apno + "'");
            s.Add(CodeIns.DBU_QUERY, "Select SUM(fAmountPaid) as payments from tblpayment where fApplicationNumber='" + apno + "'");
            s.Add(CodeIns.DBU_END);

            p.ProcessCompleted += new EventHandler(delegate
            {
                p.SafeCall(this, delegate
                {
                    if (p.State == ProcessorFlag.DataRdyErr ||
                        p.State == ProcessorFlag.Error ||
                        p.State == ProcessorFlag.ReadyErr)
                    {
                        Confirm.Error("Payment error", p.GetProcessorMessage);
                        return;
                    }
                    DataCache pay;
                    p.DataFetch(out pay);
                    pay.SetActivePage(0);
                    //Check for a positive result
                    int res = pay.GetRecordCount(0);
                    if (res != 0)
                    {
                        optannual.Enabled = false;
                        optquarterly.Enabled = false;
                        string manpay;
                        manpay = pay.GetValue(0, "fMannerPayment").ToString();
                        if (manpay.Equals("Annually"))
                        {
                            optannual.Checked = true;
                        }
                        else
                        {
                            optquarterly.Checked = true;
                            for (int i = 0; i < res; i++)
                            {
                                int qr;
                                qr = int.Parse(pay.GetValue(i, "quarter").ToString());
                                switch (qr)
                                {
                                    case 1:
                                        {
                                            chkfirst.Checked = true;
                                            chksecond.Enabled = true;
                                        }
                                        break;
                                    case 2:
                                        {
                                            chksecond.Checked = true;
                                            chksecond.Enabled = false;
                                            chkthird.Enabled = true;
                                        }
                                        break;
                                    case 3:
                                        {
                                            chkthird.Checked = true;
                                            chkthird.Enabled = false;
                                            chkfourth.Enabled = true;
                                        }
                                        break;
                                    case 4:
                                        {
                                            chkfourth.Checked = true;
                                            chkfourth.Enabled = false;
                                        }
                                        break;
                                }
                            }
                            //Check for total payments made
                            pay.SetActivePage(1);
                            paymade = Decimal.Parse(pay.GetValue(0, "payments").ToString());
                            decimal bal = Decimal.Parse(lbltotalassessedtax.Text) - paymade;
                            lblbalance.Text = bal.ToString();
                        }
                    }
                    else
                    {
                        decimal total;
                        lblbalance.Text = lbltotalassessedtax.Text;
                        total = Decimal.Parse(lblbalance.Text);
                        lbltotalamountdue.Text = total.ToString("##,###.00");
                        txtamtpaid.Value = total;
                        return;
                    }
                    decimal b = Decimal.Parse(lblbalance.Text);
                    if (b == 0)
                    {
                        btnsavepayment.Enabled = false;
                        btnprintreceipt.Enabled = true;
                    }
                    else
                    {
                        btnprintreceipt.Enabled = false;
                        btnsavepayment.Enabled = true;
                    }
               });
            });
            p.Run(s);
        }
        void gettotal()
        {
            double tax;
            tax = Double.Parse(lbltotalassessedtax.Text);
           
    
        }
        void getnextorno()
        {
            CodeScript s = new CodeScript("OFFICIAL");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

            // s.Add(CodeIns.DBU_QUERY, "SELECT concat(fUID,',',fPCount) AS fconcatresult FROM tblusers ORDER BY fUID ASC");
            s.Add(CodeIns.DBU_QUERY, "Select MAX(fIncrORNo) as orno from tblorno where fFirstCode="+firstcode);
            s.Add(CodeIns.DBU_END);

            CodeProcessor p = new CodeProcessor(ThreadingMode.Exclusive);
            p.ProcessCompleted += new EventHandler(delegate
            {
                p.SafeCall(this, delegate
                {
                    if (p.State == ProcessorFlag.DataRdyErr ||
                        p.State == ProcessorFlag.Error ||
                        p.State == ProcessorFlag.ReadyErr)
                    {
                        Confirm.Error("Error Getting Last OR Number", p.GetProcessorMessage);
                        return;
                    }
                    DataCache d;
                    p.DataFetch(out d);
                    d.SetActivePage(0);
                    int rec = d.GetRecordCount(0);
                    int lastorno, neworno;
                    string orn;
                    if (rec != 0)
                    {
                        orn = d.GetValue(0, "orno").ToString();
                        if (orn.Equals("") || orn.Equals(null))
                        {
                            lastorno = 0;
                        }
                        else
                        {
                            lastorno = int.Parse(orn);
                        }
                    }
                    else
                    {
                        lastorno=0;
                    }
                    neworno = lastorno + 1;
                    lblorno.Text = firstcode + "-" + neworno.ToString("00000");
                });
            });
            p.Run(s);
        }
        void printreceipt()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.DefaultPageSettings.PaperSize = new PaperSize("Custom", 850, 650);
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float tHt = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 10f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;
            //e.Graphics.DrawImage(pictureBox1.Image, new Rectangle(100, 35, 100, 100));
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("Republic of the Philippines", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            y += tHt;
            e.Graphics.DrawString("PROVINCE OF BENGUET", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            y += tHt;
            e.Graphics.DrawString("T U B L A Y", cFont, Brushes.Black, (lw + 100) / 2, y, sf);

            y += tHt;
            y += tHt;
            //SubTitle
            cFont = new Font("Arial", 10f, FontStyle.Bold);
            e.Graphics.DrawString("OFFICIAL RECEIPT No. " + lblorno.Text, cFont, Brushes.Black, (lw + 100) / 2, y, sf);

            cFont = new Font("Arial", 10f, FontStyle.Italic);
            y += tHt;
            e.Graphics.DrawString("TAX YEAR " + txtcalyr.Text, cFont, Brushes.Black, (lw + 100) / 2, y, sf);

            //Line
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));
            y += tHt;
            if (optannual.Checked == true)
            {
                m = "Annual";
            }
            else
            {
                m = "Quarterly";
            }
            e.Graphics.DrawString("Application Number: " + lblApplicationNumber.Text, cFont, Brushes.Black, lm + 380, y, new StringFormat());
            y += tHt;
            y += tHt;
            e.Graphics.DrawString("Date of payment: " + txtdatepayment.Value.ToString("yyyy-MM-dd"), cFont, Brushes.Black, lm + 20, y, new StringFormat());
            y += tHt;
            y += tHt;
            e.Graphics.DrawString("Received from " + lblfullname.Text + " the amount of Php " + txtamtpaid.Value.ToString("##,###.00") + " as payment for the remaining balance of " + lblbalance.Text + " " + m + " tax.", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            y += tHt;
            e.Graphics.DrawString("Payment received by: " + lbltreasuryassessor.Text, cFont, Brushes.Black, lm + 20, y, new StringFormat());
            //Line
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));
        }

     
    }
}
